package com.sandyz.virtualcam.ui

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.sandyz.virtualcam.R
import java.io.BufferedReader
import java.io.File
import java.io.FileOutputStream
import java.io.FileReader
import java.io.IOException

/**
 * 逻辑全都被注释了，现在这个Activity还没什么用
 * 因为之前设置url的方式有问题（权限）
 *
 * 待设计一个方便配置各个app虚拟摄像头视频的ui界面
 *
 * 主界面Activity
 * 
 * 主要功能：
 * 1. 视频流URL配置
 * 2. 本地视频预览
 * 3. 存储权限管理
 * 4. 配置持久化
 * 
 * 实现细节：
 * - 使用SurfaceView进行视频预览
 * - 支持本地和网络视频源
 * - 自动处理存储权限
 * - 配置文件持久化存储
 * 
 * @author sandyz987
 * @date 2023/11/18
 */
class MainActivity : AppCompatActivity() {
    // 1. 常量定义
    companion object {
        var URI_PATH_ROOT = ""  // 配置文件根目录
        const val URI_FILE_NAME = "stream.txt"  // 配置文件名称
        var uriString = ""  // 当前视频流URL

        /**
         * 1.1 获取视频流URL
         * 
         * 处理流程：
         * 1.1.1 检查目录是否存在
         * 1.1.2 读取配置文件
         * 1.1.3 返回URL
         * 
         * @return String 视频流URL
         */
        fun getUri(): String {
            var uri = ""
            try {
                // 1.1.1 检查目录
                File(URI_PATH_ROOT).let {
                    if (!it.exists())
                        it.mkdirs()
                }
                // 1.1.2 读取配置
                File(URI_PATH_ROOT + URI_FILE_NAME).let {
                    if (!it.exists()) {
                        it.createNewFile()
                    }
                    val reader = BufferedReader(FileReader(it))
                    uri = reader.readLine() ?: ""
                    reader.close()
                }
            } catch (e: IOException) {
                e.printStackTrace()
                return e.toString()
            }
            return uri.also { uriString = it }
        }
    }

    // 2. 权限回调
    private var afterRequestPermissionCallback: (() -> Unit)? = null

    /**
     * 3. Activity创建
     * 
     * 处理流程：
     * 3.1 初始化UI
     * 3.2 设置Surface预览
     * 3.3 设置按钮事件
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 3.1 初始化UI组件
        val btnLocal = findViewById<Button>(R.id.btn_local)
        val btnSav = findViewById<Button>(R.id.btn_sav)
        val etUri = findViewById<EditText>(R.id.et_uri)

        // 3.2 设置Surface预览
        val surfaceView = findViewById<SurfaceView>(R.id.surfaceView)
        surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                // 3.2.1 创建预览画布
                holder.lockCanvas()?.let {
                    it.drawColor(0xffff0000.toInt())
                    it.drawText("Hello World", 100f, 100f, TextView(this@MainActivity).paint)
                    holder.unlockCanvasAndPost(it)
                }
            }

            override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
                // 3.2.2 预览尺寸变化
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
                // 3.2.3 预览销毁
            }
        })

//        doIfPermission {
//            etUri.setText(getUri())
//        }

        // 3.3 设置保存按钮事件
        btnSav.setOnClickListener {
            doIfPermission {
                // 3.3.1 创建配置目录
                val dir = File(URI_PATH_ROOT)
                if (!dir.exists()) {
                    val mkd = dir.mkdirs()
                    Toast.makeText(this@MainActivity, "创建目录：$mkd", Toast.LENGTH_SHORT).show()
                }

                // 3.3.2 处理URL
                etUri.setText(etUri.text.toString().replace("https", "http").replace("\n", ""))
                val uri = etUri.text.toString()
                uriString = uri

                // 3.3.3 保存配置
                val file = File(URI_PATH_ROOT + URI_FILE_NAME)
                try {
                    if (!file.exists()) {
                        file.createNewFile()
                    }
                    val fos = FileOutputStream(file)
                    fos.write(uri.toByteArray())
                    fos.close()
                    Toast.makeText(this@MainActivity, "设置成功，内容保存在：$URI_PATH_ROOT$URI_FILE_NAME", Toast.LENGTH_SHORT).show()
                } catch (e: Exception) {
                    Toast.makeText(this, "设置失败：${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * 4. 权限检查
     * 
     * @param callback 权限获取后的回调
     */
    private fun doIfPermission(callback: (() -> Unit)?) {
        if (!hasPermission()) {
            requestPermission()
            afterRequestPermissionCallback = callback
        } else {
            callback?.invoke()
        }
    }

    /**
     * 4.1 请求权限
     */
    private fun requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED
                || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED
            ) {
                requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
            }
        }
    }

    /**
     * 4.2 检查权限
     * 
     * @return Boolean 是否有权限
     */
    private fun hasPermission(): Boolean {
        val bool = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_DENIED
                    && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_DENIED)
        } else true
        if (!bool) {
            Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
        }
        return bool
    }

    /**
     * 5. 权限请求结果处理
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isNotEmpty() && requestCode == 1) {
            if (grantResults[0] != PackageManager.PERMISSION_DENIED) {
                if (afterRequestPermissionCallback != null) {
                    afterRequestPermissionCallback?.invoke()
                    afterRequestPermissionCallback = null
                } else {
                    Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}